# 1..尝试抓取豆瓣的数据(https://movie.douban.com/tv/)
#    <1>豆瓣中的选电视剧页面, 查看可播放的电视中12部电视的数据
#    <2>将该页中的电视剧名字, 评分, 有多少集拿到
#
#   <3>将数据保存到csv文件 中

import requests


def douban():

    url =f'https://m.douban.com/rexxar/api/v2/tv/recommend/'

    params = {
        "refresh": "0",
        "start": "0",
        "count": "20",
        "selected_categories": "{}",
        "uncollect": "false",
        "tags": ""
    }
    headers = {
        'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50',
        'Referer': 'https://movie.douban.com/tv/'
    }
    # 获取网页源代码, 它是字符串类型
    # r = requests.get(url, params=params, headers=headers).text
    # 获取网页源代码, 它是字典类型
    r = requests.get(url, params=params, headers=headers).json()
    print(r)
    items = r['items']
    for item in items:
        # 电视评分
        rating = item.get('rating')
        print(rating)
        if rating:

            # 电视名字
            title = item['title']
            # 演员
            actor = item['card_subtitle']
            # 上映时间
            year = item['year']
            # 电视评分
            value = rating['value']
            # print(title, value,actor,year)
            f.write(f'{title},{actor},{year},{value}\n')


if __name__ == '__main__':
    with open('豆瓣网.csv','w',encoding='utf-8-sig') as f:
        f.write('电视名字,演员,上映时间,电视评分\n')
        for page in range(1,3):
            douban()
